<template>
    <!-- accept="image/gif, image/jpeg" -->
    <!-- accept="*/*"   capture="camera"-->
 	<van-uploader class="reporting-upload" :after-read="onRead" :accept="accept"  >
        <!-- <van-icon v-show='!showFile' name="add-o" class="reporting-icon" /> -->
        <i v-show='type!="video"&&!showFile' class="fa fa-camera reporting-icon" aria-hidden="true"></i>
        <i v-show='type=="video"&&!showFile' class="fa fa-video-camera reporting-icon" aria-hidden="true"></i>
        <img :id='imgId' v-show='showFile' :src='showFile' style="width: 100%; height: 100%;">
    </van-uploader>
</template>
<script>
export default {
    name: 'upload',
    props: ['type'],
    data() {
        return { showFile: '', accept: '',imgId:'' };
    },
    mounted() {
        this.imgId="uploadImg_"+this.guid();
        if (this.type == 'video') {
            this.accept = 'video/*;capture=camera';
        } else {
            this.accept = 'image/*;capture=camera';
        }
    },
    methods: {
        onRead(file) {
            // this.showFile = file.content;
            // file.content=file.content.split(',')[1];
            // this.$emit('img', file);
            // this.$emit('input', file.content);
            this.showFile = file.content;
            let fileSize=1024*1000;            
            if((/^image\//.test(file.file.type))&&(file.file.size > fileSize)) {
              let image=document.getElementById(this.imgId);
                image.onload = ()=> {        
                let canvas = document.createElement("canvas");
                let newSize= fileSize/file.file.size;
                canvas.width = image.naturalWidth; 
                canvas.height = image.naturalHeight; 
                canvas.getContext("2d").drawImage(image, 0, 0);  
                let canvasDataURL = canvas.toDataURL(file.file.type,newSize );
                file.content=canvasDataURL.split(',')[1];
                file.size=newSize;
                this.$emit('img', file);
                this.$emit('input', file.content);
            };
         }else{
            file.content=file.content.split(',')[1];
            this.$emit('img', file);
            this.$emit('input', file.content.split(',')[1]);
          }
        },
        guid() {
               var  S4=()=> {
                return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
                }
            return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
        }   
    },
};
</script>
<style scoped>
.reporting-upload {
    /*border: 1px solid #a7a6a6;*/
    width: 98%;
    height: 103%;  
    margin: 6px;
    display: table;
    text-align: center;
}
.reporting-icon {
    font-size: 50px;
    margin: 50px 100px;
    display: table-cell;
    vertical-align: middle;
}



.van-icon-add-o::before {
    color: #a7a6a6;
}



</style>
